import { getUserLoginInfo, login, logoff, verificationCaptcha } from '@/infra/api/user'
import { getToken, removeToken, setToken, setUserInfo } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import store from '@/store'
import TableSetting from '@/framework/components/table/TableSetting'
import { EventBus } from '@/framework/infra/event/EventBus'
import EventNames from '@/infra/event/EventNames'
import { aesEncryption } from '@/utils/crypto'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    permission: [],
    routes: [],
    allPermission: {},
    menuAll: [],
    counter: -1
  }
}

const state = getDefaultState()

function calcAllPermission(menus) {
  for (let i = 0; i < menus.length; i++) {
    const menu = menus[i]
    if ((menu.children && menu.children.length) || (menu.buttons && menu.buttons.length)) {
      state.allPermission[menu.name] = false // 非子节点
    } else {
      state.allPermission[menu.name] = true // 子节点
    }
    if (menu.children && menu.children.length) {
      calcAllPermission(menu.children)
    } else if (menu.buttons && menu.buttons.length) {
      calcAllPermission(menu.buttons)
    }
  }
}

function _filerRoutes(routes) {
  if (store.getters.superAdmin) {
    return routes
  }
  const permission = store.getters.permission
  return routes.filter(el => !el.name || el.name === 'dashboard' || permission.some(code => code.startsWith(el.name))).map(el => {
    el = { ...el }
    if (el.children) {
      el.children = _filerRoutes(el.children)
      if (!el.children.length) {
        return null
      }
    } else if (el.buttons && el.buttons.length) {
      // if (el.buttons.some(el => el.name === 'cmt:complain-follow-up:follow')) {
      //   debugger
      // }
      // if (!permission.some(code => code.startsWith(el.buttons[0].name))) {
      //   return null
      // }
      el.buttons = _filerRoutes(el.buttons)
      if (!el.buttons.length) {
        return null
      }
    }
    return el
  }).filter(el => el)
}

const mutations = {
  RESET_STATE: (state) => {
    state.token = ''
    // Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.userInfo.name = name
    // setUserInfo(state.userInfo)
  },
  SET_ROUTES: (state, routes) => {
    console.log("routes: ", routes)
    router.addRoutes(routes)
    state.menuAll = routes.map(el => {
      el = { ...el }
      el.label = el.meta && el.meta.title || ''
      if (el.children) {
        el.children = el.children.map(i => {
          i.label = i.meta && i.meta.title || ''
          return { ...i, children: undefined }
        })
      }
      return el
    })
    state._initRoutes = [...router.options.routes, ...routes]
    // console.log(state._initRoutes)
    calcAllPermission(state.menuAll)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission?.map(el => el.permissionCode) || []
    state.routes = _filerRoutes(state._initRoutes)
    console.log(state.routes)
  },
  SET_USERIFNO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_COUNTER: (state, counter) => {
    state.counter = counter
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, captchaVerification, captcha } = userInfo
    return new Promise((resolve, reject) => {
      verificationCaptcha(captcha)
      .then(response => {
        if(response.code === '1') {
          return login({
            username: username.trim(),
            businessType: 1,
            password: aesEncryption(password),
            captchaVerification,
          })
        } else {
          throw new Error('图片验证码检验失败')
        }
      })
      .then(result => {
        console.log(result)
        commit('SET_TOKEN', result)
        commit('SET_NAME', username.trim())
        resolve()
      })
      .catch(error => {
        reject(error)
      })
    })
  },
  getInfo({
    commit
  }) {
    return getUserLoginInfo().then((data) => {
      TableSetting.saveDefaultSearchParam({
        storeId: data.storeId > 0 ? data.storeId : null
      })
      EventBus.emit(EventNames.onFresh)
      commit('SET_USERIFNO', data)
      commit('SET_PERMISSION', data.permissList || [])
      commit('SET_COUNTER', data.counter)
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      EventBus.emit(EventNames.logoff)
      removeToken() // must remove  token  first
      resetRouter()
      // commit('RESET_STATE')
      commit('SET_USERIFNO', {})
      commit('SET_TOKEN', null)
      commit('SET_PERMISSION', [])
      // commit('SET_NAME', loginName.trim())
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

